
var DEFAULT_ENCODING = 'utf8';
var CODING_TYPE = '0100';

function encode(data, encoding) {
	encoding = encoding || DEFAULT_ENCODING;
	return new Buffer(data, encoding)
		.toString('hex')
		.match(/.{1,2}/g)
		.map( function(c) {
			return new Buffer(c, 'hex')
				.toString('binary')
				.charCodeAt(0)
				.toString(2);
		})
		.reduce( function(res, c) {
			return res + normalizeBin(c);
		}, "");
}

function normalizeBin(data) {
	return !(data.length % 8) ? data : normalizeBin('0' + data);
}

function decode(data) {
	return new Buffer(data
			.match(/.{1,8}/g)
			.map( function(c) {
				return new Buffer(String.fromCharCode(parseInt(c, 2)), 'binary')
					.toString('hex');
			})
			.join(""), 'hex')
		.toString('utf8');
}

module.exports = {
	encode: encode,
	decode: decode,
	normalizeBin: normalizeBin,
};
